<?php
namespace control;


/*
*归档管理类
*/


class archiveClass extends adIndexClass
{
    private const page = 'archive';
    private const table = 'archive';
    private const title = '归档管理';
    public array $stateOption = ['待归档', '已归档'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'fileBtn'      => [
                        'name'  => "附件数量",
                        'width' => 150,
                    ],
                    'type' => [
                        'name'  => "源分类",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => "文号",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'transferStid'         => [
                        'name'  => '移交人',
                        'width' => 150,
                    ],
                    'department'          => [
                        'name'  => '移交部门',
                        'width' => 150,
                    ],
                    'name'          => [
                        'name'  => '题名',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'pageNum'          => [
                        'name'  => '页数',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'partNum'          => [
                        'name'  => '份数',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'fileDate'          => [
                        'name'  => '文件形成日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'level'          => [
                        'name'  => '密级',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'workFlow'          => [
                        'name'  => '归档标识',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "状态" => checkbox(array('name'=>'workFlow','value'=>['待归档','已归档'],'checked'=>['待归档'])),
                ],
                [
                    "源分类" => repeatSelect(array("name" => "type",'sqlField'=>'type','sqlForm'=>self::table)),
                    "文号"     => text(array("name" => "orderNo")),
                    "题名"     => text(array("name" => "name")),
                ],
                [
                    '移交部门'   => selectMultiple(array("name" => "department", "class" => "width200",'table'=>"department",'sqlId'=>'id','sqlField'=>'name')),
                    "密级" => select(array("name" => "level", "option" =>explode('，',para('secretLevelOption')))),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','addArchive',{formName:'listForm'})\" class='spanButton'>归档</span>\n";
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">退回</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//车牌号
            "name" => $this->post('name'),//车辆品牌
        );
        //全等查询数组
        $equal = array(
            "transferDept" => $this->post('department'),//车辆编号
            "level" => $this->post('level'),//状态
            "carType" => $this->post('type'),//类型
        );
        $and = '';
        if ($this->post('workFlow')){
            $and.=" and workFlow in ('".implode("','",$this->post('workFlow'))."')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "fileBtn":
                        $num = static::total(array('table' => 'file', 'where' => "targetId = '" . $array['targetId'] . "'"));
                        $fileBtn = $num > 0 ? "<span class='link' onclick=\"layer('component','fileDetail',{id:'" . $array['targetId'] . "'})\">" . $num . "</span>" : '';
                        $row[] = $fileBtn;
                        break;
                    case "department":
                        $department = query('department',"id = '$array[transferDept]'");
                        $row[] = $department['name'];
                        break;
                    case "transferStid":
                        $row[] = self::findStaff($array['transferStid']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(partNum),0) as partNum",
        ]);
        $total    = [
            'partNum'        => $totalQuery['partNum'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }
    /**
     * 归档
     */
    public function addArchive(): bool|string
    {
        $formName = $this->post('formName');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must."归档日期：" => text(array('name'=>'archiveDate','laydate'=>[])),
                must."全宗号：" => select(array('name'=>'serialStr','option'=>explode(',',para('serialStr')),'title'=>'全宗号')),
            ),
            array(
                must."部门名称：" => selectMultiple(array("name" => "departmentId", "title" => "部门名称",'table'=>"department",'sqlId'=>'id','sqlField'=>'name')),
                "分类：" => selectMultiple(array("name" => "typeId", "title" => "分类",'table'=>"archive_type",'sqlId'=>'id','sqlField'=>'name'))
            ),
            array(
                must."归档年度：" => text(array('name'=>'archiveYear','laydate'=>['type'=>'year'],'value'=>date('Y'))),
               "页数：" => text(array('name'=>'pageNum')),
            ),
            array(
                "份数：" => text(array('name'=>'partNum')),
                "保管期限：" => select(array('name'=>'saveTime','option'=>explode('，',para('archiveSaveTime')),'title'=>'保管期限')),
            ),
            array(
                "存放位置：" => selectMultiple(array("name" => "locationId", "title" => "存放位置",'table'=>"archive_cabinet",'sqlId'=>'id','sqlField'=>'name'))
            ),
            array(
                '备注'=>textarea(array('name'=>'text','class'=>'textarea'))
            )

        )));
        //返回
        return $this->layer(array("title" => "归档", "height" => 400, "width" => 800, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 归档
     */
    public function addArchiveEdit(): bool|string
    {
        $idArr = $this->post('id')?[$this->post('id')]:$this->post('listId');
        $field = [
            'archiveDate'=>$this->post('archiveDate'),
            'serialStr'=>$this->post('serialStr'),
            'departmentId'=>$this->post('departmentId'),
            'typeId'=>$this->post('typeId'),
            'archiveYear'=>$this->post('archiveYear'),
            'saveTime'=>$this->post('saveTime'),
            'locationId'=>$this->post('locationId'),
            'text'=>$this->post('text'),
            'pageNum'=>$this->post('pageNum'),
            'partNum'=>$this->post('partNum'),
        ];
        $annotation = [
            'archiveDate' => '归档日期',
            'serialStr' => '全宗号',
            'departmentId' => '部门名称',
            'archiveYear' => '归档年度',
        ];
        $rules = [
            'archiveDate' => 'required|date',
            'serialStr' => 'required',
            'departmentId' => 'required',
            'archiveYear' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        }elseif ($result === false){
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        }else {
            $this->startTrans();
            $archive_cabinet = query('archive_cabinet',"isDefault = 1");
            $archive_type = query('archive_type',"isDefault = 1");
            $field['typeId'] = $field['typeId']?:$archive_type['id'];
            $field['locationId'] = $field['locationId']?:$archive_cabinet['id'];
            $field['transferDate'] = $this->date;
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if ($info['workFlow'] != '待归档'){
                    $json['warn'] = "档案【{$info['name']}】归档失败，不是待归档状态<br>";
                    break;
                }else{
                    $insertField = [
                        'id'=>self::getId(),
                        'orderNo'=>self::archiveOrderNo($field['departmentId'],$field['serialStr']),
                        'transferStid'=>$info['transferStid'],
                        'transferDept'=>$info['transferDept'],
                        'name'=>$info['name'],
                        'preText'=>$info['orderNo'],
                        'fileDate'=>$info['fileDate'],
                        'level'=>$info['level'],

                        'source'=>'归档管理',
                        'stid'=>self::$stid,
                        'sourceId'=>$info['id']
                    ];
                    $insertField = array_merge($insertField,$field);
                    $warn = static::insert(array(
                        'table'=>'archive_file',
                        'field'=>$insertField,
                    ));
                    $bool = static::update(array('table'=>'archive','field'=>['workFlow'=>'已归档'],'where'=>"id = '$info[id]'"));
                    if ($bool !='更新成功'){
                        $warn = '更新归档状态失败';
                    }
                    $bool = $this->updateObject($info['id']);
                    if ($bool !='更新成功'){
                        $warn = $bool;
                    }
                    if (in_array($warn,['新增成功','更新成功'])) {
                        $x++;
                        $text .= $this->control['name'] . "归档公文【{$info['name']}】， id：{$id}成功<br>";
                    } else {
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (empty($json['warn'])) {
                $this->commitTrans();
                if ($text) {
                    //添加日志
                    $this->logText(["type" => self::page, "text" => $text]);
                }
                $_SESSION['warn'] = "成功归档了{$x}个档案，详情请查看系统日志";
                $json['warn'] = 2;
            }else{
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 生成归档号
     */
    public static function archiveOrderNo($departmentId,$serialStr): string
    {
        $orderNo = '';
        if (empty($departmentId) || empty($serialStr)){
            return $orderNo;
        }
        $department = query('department',"id = '$departmentId'");
        $prefix = PYClass::encode($serialStr,strtoupper:true).'-'.date('Y').'-'.PYClass::encode($department['name'],strtoupper:true).'-';
        $archive_file = query('archive_file',"orderNo like '%$prefix%' order by orderNo desc");
        if (!empty($archive_file['id'])){
            $splitArr = explode('-',$archive_file['orderNo']);
            $number = end($splitArr);
            $orderNo =$prefix.sprintf("%04d",(int)$number+1);
        }else{
            $orderNo =$prefix.sprintf("%04d",1);
        }
        return $orderNo;
    }
    /**
     * 更新归档管理中对应数据的归档状态
     */
    public function updateObject($id): string
    {
        $info = query(self::table,"id = '$id'");
        switch ($info['type']){
            case '公文发文':
            case '公文收文':
                return static::update(array('table'=>'official_document','field'=>['isArchive'=>'已归档'],'where'=>"id = '$info[targetId]'"));
            case '合同管理':
                return static::update(array('table'=>'contract','field'=>['isArchive'=>'已归档'],'where'=>"id = '$info[targetId]'"));
            default:
                return '未找到类型';
        }
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($info['workFlow'] =='待归档' && $this->power(self::page,'edit')){
                $button[] = [
                    "name" => '退回',
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('" . $this->get('cla') . "','operate',{id:'{$info['id']}'})",
                ];
                $button[] = [
                    "name" => '归档',
                    "type" => "点击事件",
                    "cla" => $this->get('cla'),
                    "fun" => "layer('" . $this->get('cla') . "','addArchive',{id:'{$info['id']}'})",
                    'style' => 'li-btn-blue-bg',
                ];
            }
            $department = query('department',"id = '$info[transferDept]'");
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '基本信息' => array(
                    array(
                        "源分类" => $info['type'],
                        "文号" => $info['orderNo'],
                        "题名" => $info['name'],
                        "页数" => $info['pageNum'],
                    ),
                    array(
                        "份数" => $info['partNum'],
                        "密级" => $info['level'],
                    ),
                ),
                '移交信息' => array(
                    array(
                        "移交人" => self::findStaff($info['transferStid']),
                        "移交部门" => $department['name'],
                        "移交日期" => $info['transferDate'],
                        "归档标识" => $info['workFlow'],
                    ),
                ),
                '附件' => [
                    [
                        fileUploadClass::showFile($info['targetId'])
                    ]
                ],
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }



    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'edit';
                $msg = '编辑' . self::title;
                $title = '是否确认退回所选的待归档的数据？';
                $word =true;
                $function = 'back';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 退回
     *
     * @return false|string
     */
    public function back(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['workFlow'] == '已归档') {
                    $warn = "退回失败：已归档";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    //返回
                    $warn = "退回成功";
                    $x++;
                }
                $text .= self::title . "题名【" . $info['name'] . "】，文号【{$info['orderNo']}】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "退回了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "退回了" . $x . "条数据，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}

